using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;

namespace ASteroids
{
    /// <summary>
    /// This is the main type for your game
    /// </summary>
    public class Game1 : Microsoft.Xna.Framework.Game
    {
        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;

        enum GameState { TitleScreen, Playing, PlayerDead, GameOver };
        GameState gameState = GameState.TitleScreen;
        
        Texture2D titleScreen;
        Texture2D spriteSheet;
        Texture2D seaBackground;
        Texture2D gameOverScreen;

        BubbelBackground bubbelBackground;
        AsteroidManager asteroidManager;
        
        CollisionHandler collisionHandler;


        AudioEngine audioEngine;
        WaveBank waveBank;
        public SoundBank soundBank;

        Effect effect;
        RenderTarget2D MainTexture;
        float blurValue = 0;
        float waterValue = 1.0f;
        int waterDirection = 1;
        int waterLoopLength = 40;
        Random rnd;
        List<PlayerObject> players;


        public Game1()
        {
            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";
        }

        /// <summary>
        /// Allows the game to perform any initialization it needs to before starting to run.
        /// This is where it can query for any required services and load any non-graphic
        /// related content.  Calling base.Initialize will enumerate through any components
        /// and initialize them as well.
        /// </summary>
        protected override void Initialize()
        {
            graphics.PreferredBackBufferWidth = 1024;
            graphics.PreferredBackBufferHeight = 768;
            graphics.IsFullScreen = true;
            
            MainTexture = new RenderTarget2D(GraphicsDevice, graphics.PreferredBackBufferWidth, graphics.PreferredBackBufferHeight);
            
            graphics.ApplyChanges();
            rnd = new Random();

            base.Initialize();
        }

        /// <summary>
        /// LoadContent will be called once per game and is the place to load
        /// all of your content.
        /// </summary>
        protected override void LoadContent()
        {
            Rectangle screenBounds = new Rectangle(0, 0, this.Window.ClientBounds.Width, this.Window.ClientBounds.Height);


            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(GraphicsDevice);
            titleScreen = Content.Load<Texture2D>(@"Texture\TitleScreen2");
            gameOverScreen = Content.Load<Texture2D>(@"Texture\GameOverScreen");

            spriteSheet = Content.Load<Texture2D>(@"Texture\SpriteSheet");
            seaBackground = Content.Load<Texture2D>(@"Texture\seaBackground");
            audioEngine = new AudioEngine(@"Content\Audio\GameAudio.xgs");
            waveBank = new WaveBank(audioEngine, @"Content\Audio\Wave Bank.xwb");
            soundBank = new SoundBank(audioEngine, @"Content\Audio\Sound Bank.xsb");

            

            players = new List<PlayerObject>();
            players.Add(new PlayerObject(
                spriteSheet,
                new Rectangle(0, 0, 48, 48),
                5,
               screenBounds));

            //players.Add(new PlayerObject(
            //    spriteSheet,
            //    new Rectangle(0, 0, 48, 48),
            //    5,
            //    screenBounds, Keys.A, Keys.D, Keys.W, Keys.LeftShift));


            bubbelBackground = new BubbelBackground(
                this.Window.ClientBounds.Width,
                this.Window.ClientBounds.Height,
                50,
                new Vector2(0, -30f),
                spriteSheet,
                new Rectangle(0, 176,32, 32));

            asteroidManager = new AsteroidManager(
                20,
                spriteSheet,
                1,
                this.Window.ClientBounds.Width,
                this.Window.ClientBounds.Height);

            collisionHandler = new CollisionHandler(asteroidManager, players);


            effect = Content.Load<Effect>(@"effects\EffectTest");

        }

        /// <summary>
        /// UnloadContent will be called once per game and is the place to unload
        /// all content.
        /// </summary>
        protected override void UnloadContent()
        {
        }

        /// <summary>
        /// Allows the game to run logic such as updating the world,
        /// checking for collisions, gathering input, and playing audio.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Update(GameTime gameTime)
        {
            // Allows the game to exit
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
                this.Exit();
            KeyboardState keyboardState = Keyboard.GetState();

            switch (gameState) { 
                case GameState.TitleScreen:
                    if (keyboardState.GetPressedKeys().Length > 0 && !keyboardState.IsKeyDown(Keys.Escape)) gameState = GameState.Playing;
                    else if (keyboardState.IsKeyDown(Keys.Escape)) this.Exit();
                    bubbelBackground.Update(gameTime);
                    break;
                case GameState.Playing:
                    if (keyboardState.IsKeyDown(Keys.Escape)) this.Exit();
                    bubbelBackground.Update(gameTime);
                    asteroidManager.Update(gameTime);
                    collisionHandler.CheckCollisions();
                   
                    for(int x = 0; x < players.Count; x++){
                        players.ElementAt(x).Update(gameTime, this.Window.ClientBounds, this);
                        if (players.ElementAt(x).Destroyed)
                        {
                            players.RemoveAt(x);
                            x--;
                        }

                    }

                    if (players.Count <= 0)
                        gameState = GameState.GameOver;

                    break;
                case GameState.PlayerDead:
                    break;
                case GameState.GameOver:
                    if (keyboardState.IsKeyDown(Keys.Escape)) this.Exit();
                    break;
            }

            blurValue += 0.001f;
            waterValue += (rnd.Next(1, 2)/3.5f) * waterDirection;
            if (blurValue > 0.1) blurValue = 0;

            if (waterValue > waterLoopLength || waterValue < 0)
                waterDirection = waterDirection * -1;
            
            base.Update(gameTime);
        }

        private void DrawGame(GameTime gameTime)
        {
            GraphicsDevice.SetRenderTarget(MainTexture);
            GraphicsDevice.Clear(Color.CornflowerBlue);

            spriteBatch.Begin();

            spriteBatch.Draw(seaBackground, new Rectangle(0, 0, this.Window.ClientBounds.Width, this.Window.ClientBounds.Height), Color.White);
            bubbelBackground.Draw(spriteBatch);

            if (gameState == GameState.TitleScreen)
            {
                spriteBatch.Draw(titleScreen, new Rectangle(0, 0, this.Window.ClientBounds.Width, this.Window.ClientBounds.Height), Color.White);
            }
            
            if ((gameState == GameState.Playing) || (gameState == GameState.PlayerDead) || gameState == GameState.GameOver)
            {
                
                asteroidManager.Draw(spriteBatch);
              
                foreach (PlayerObject targetPlayer in players) {
                    targetPlayer.Draw(spriteBatch);
                }
            }

            if (gameState == GameState.GameOver) {
                spriteBatch.Draw(gameOverScreen, new Rectangle(0, 0, this.Window.ClientBounds.Width, this.Window.ClientBounds.Height), Color.White);
            
            }

            spriteBatch.End();

            GraphicsDevice.SetRenderTarget(null);
        }
 
        /// <summary>
        /// This is called when the game should draw itself.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Draw(GameTime gameTime)
        {
           
            DrawGame(gameTime);

            GraphicsDevice.Clear(Color.CornflowerBlue);
           
            spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend);
            
            effect.CurrentTechnique = effect.Techniques["test"];
            effect.Parameters["blurRadius"].SetValue(waterValue);
            effect.Parameters["timeraslow"].SetValue(waterValue);

            
            effect.CurrentTechnique.Passes["Water"].Apply();
            
            spriteBatch.Draw(MainTexture, Vector2.Zero, Color.White);
            
            spriteBatch.End();

            base.Draw(gameTime);
        }

        public void PlayCue(string cueName) {
            this.soundBank.PlayCue(cueName);
        }
        
    }
}
